﻿using ProjectScheduling.daos;
using ProjectScheduling.models;
using System.Data;
using System.Windows.Forms;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace ProjectScheduling
{
    public partial class SchedulingPage : UserControl
    {
        public static readonly SchedulingPage b = new();
        public DateTime CurrDay = DateTime.Today;
        private readonly DataTable _table = new();
        private (int page, int total) _pages = (1, 0);
        private List<Projects> TableData = [];
        int rowSize = 40;
        public SchedulingPage()
        {

            InitializeComponent();
            view_all.Columns["a_13"].DefaultCellStyle.NullValue = null;
            txt_search_pagesize.Text = "40";
            txt_search_pagesize.SelectedIndexChanged += (o, e) =>
            {
                rowSize = Convert.ToInt32(txt_search_pagesize.Text);
                Search();
            };
            view_all.AutoGenerateColumns = false;
            view_all.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            void columns(params string[] cols) => cols.ToList().ForEach(col => _table.Columns.Add(col));
            columns("Id", "Name", "ProjectTypeName", "StaffName", "FromDate", "ToDate", "StateStr", "State", "Rate", "CustomerName", "OwnerShip", "PreparedDatas", "StaffChange", "AllDays", "Score");
            Init();

            _pages = (1, 0);
            Search();

        }
        private void Init()
        {
            txt_search_state.SelectedIndex = 0;
            txt_search_from.Text = "";
            txt_search_to.Text = "";
            txt_search_username.Text = "";
            txt_search_projectname.Text = "";
        }
        private void SchedulingPage_Resize(object sender, EventArgs e)
        {
            view_all.Columns["a_4"].Visible = Width > 700;
            view_all.Columns["a_5"].Visible = Width > 700;
            view_all.Columns["a_2"].Visible = Width > 500;
            view_all.Columns["a_3"].Visible = Width > 500;
            view_all.Columns["a_0"].Visible = false;
        }

        private void Txt_search_from_ValueChanged(object sender, EventArgs e)
        {
            SetTimeFormat(sender);
        }

        private void SchedulingPage_VisibleChanged(object sender, EventArgs e)
        {
            Init();
            _pages = (1, 0);
            Search();
        }


        private void Txt_search_from_MouseUp(object sender, MouseEventArgs e)
        {
            SetTimeTag(sender);
        }

        private static void SetTimeTag(object obj)
        {
            if (obj is not DateTimePicker picker) return;
            picker.Tag = true;
        }

        static void SetTimeFormat(object obj)
        {
            if (obj is not DateTimePicker picker) return;
            if (picker.Tag is not null)
            {
                picker.CustomFormat = "yyyy-MM-dd";
            }
        }

        private void Btn_search_clear_Click(object sender, EventArgs e)
        {
            Init();
            txt_search_username.Text = "";
            txt_search_projectname.Text = "";
            _pages = (1, 0);
            Search();
        }
        private void Search()
        {
            var username = txt_search_username.Text?.Trim() ?? "";
            var projectname = txt_search_projectname.Text?.Trim() ?? "";
            var start = txt_search_from.Text?.Trim() ?? "";
            var end = txt_search_to.Text?.Trim() ?? "";
            var _start = DateTime.TryParse(start, out DateTime _s) ? _s : DateTime.MinValue;
            var _end = DateTime.TryParse(end, out DateTime _e) ? _e : DateTime.MaxValue;
            var _stateIndex = txt_search_state.SelectedIndex;
            var _state = (Enum_ProjectState)Math.Pow(2, _stateIndex);
            var page = _pages.page;
            var pagesize = Convert.ToInt32(txt_search_pagesize.Text);

            var list = ProjectDao.Base.FindAll1(page, rowSize, it =>
                it.State != Enum_ProjectState.待排期 &&
                (string.IsNullOrEmpty(username) || it.StaffsList.Any(z => !string.IsNullOrEmpty(z.UserName) && z.UserName.Contains(username))) &&
                (string.IsNullOrEmpty(projectname) || (!string.IsNullOrEmpty(it.Name) && it.Name.Contains(projectname))) &&
                it.FromDate <= _end && it.ToDate >= _start &&
                (_stateIndex == 0 || it.State == _state));
            ToTable(TableData = (list.Items ?? []));
            _pages = (_pages.page, (int)Math.Ceiling((list?.Total ?? 0m) / rowSize));
            //lb_page.Text = $"总条数：{list?.Total}   总页数：{Math.Ceiling((list?.Total ?? 1m) / 20)}";
            lb_page.Text = $"第{_pages.page}页/共{_pages.total}页 共{list?.Total ?? 0}条";
            btn_first.Enabled = _pages.page > 1;
            btn_prev.Enabled = _pages.page > 1;
            btn_next.Enabled = _pages.total > _pages.page;
            btn_last.Enabled = _pages.total > _pages.page;
        }
        void ToTable(List<Projects> list)
        {
            _table.Rows.Clear();
            var proids = list.Select(p => p.Id).ToList();
            var typeids = list.Select(p => p.ProjectTypeId).ToList();
            if (proids.Count == 0) return;
            //var staffids = ProjectStaffDao.Base.FindAll(it => proids.Contains(it.ProjectId));
            var types = ProjectTypeDao.Base.FindAll(it => typeids.Contains(it.Id));
            list.ForEach(item =>
            {
                if (item == null) return;
                var row = _table.NewRow();
                row["Id"] = item.Id;
                row["Name"] = item.Name;
                row["StateStr"] = item.State.ToString();
                row["FromDate"] = item.FromDate.ToString("yyyy-MM-dd") ?? "";
                row["ToDate"] = item.ToDate.ToString("yyyy-MM-dd") ?? "";
                row["StaffName"] = string.Join("、", item.StaffsList?.Select(it => it.UserName) ?? []);
                row["ProjectTypeName"] = item.ProjectType?.Name ?? "";
                row["State"] = (int)item.State;
                row["Rate"] = item.Rate.ToString() + "%";
                row["CustomerName"] = item.CustomerName ?? "";
                row["OwnerShip"] = item.OwnerShip;
                row["PreparedDatas"] = item.PreparedDatas?.Count > 0 ? "工时记录" : string.Empty;
                row["StaffChange"] = new List<Enum_ProjectState> { Enum_ProjectState.已排期, Enum_ProjectState.实施中 }.Contains(item.State) ? "人员变更" : string.Empty;
                row["Score"] = item.Score;
                if (item.PreparedDatas?.Count > 0)
                {
                    var lst = PreparedDataDao.Base.FindAll(it => it.ProjectId == item.Id) ?? [];
                    row["AllDays"] = lst.Sum(it => it.PrepardStaffs?.Sum(item => item.Days));
                }

                _table.Rows.Add(row);
            });
            view_all.DataSource = _table;
        }

        private void Btn_search_Click(object sender, EventArgs e)
        {
            _pages = (1, 0);
            Search();
        }
        /// <summary>
        /// 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void View_all_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            var data = TableData.ElementAt(e.RowIndex);
            if (data == null) return;
            //var id = int.Parse(view_all.Rows[e.RowIndex].Cells["a_0"].Value?.ToString() ?? "0");
            switch (e.ColumnIndex)
            {
                case 11:
                    if (data.State == Enum_ProjectState.已完结 && data.Score == 0)
                    {
                        var f = new Form
                        {
                            Width = 300,
                            Height = 140,
                            StartPosition = FormStartPosition.CenterParent,
                            AllowDrop = false,
                            FormBorderStyle = FormBorderStyle.FixedSingle,
                            Text = "工作量评分"
                        };
                        f.Controls.Add(new Label
                        {
                            Location = new Point(20, 25),
                            Text = "工作量评分",
                            AutoSize = true
                        });
                        var txt = new TextBox
                        {
                            Location = new Point(100, 20),
                            Text = "",
                            Size = new Size(100, 20)
                        };
                        f.Controls.Add(txt);
                        var button = new Button
                        {
                            Location = new Point(100, 60),
                            Size = new Size(80, 30),
                            Text = "更新",
                        };
                        button.Click += (o, e) =>
                        {
                            if (!int.TryParse(txt.Text, out int _sc))
                            {
                                MessageBox.Show("工作量评分无效");
                                return;
                            }
                            if (MessageBox.Show("是否确认更新工作量？", "操作确认", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                data.Score = _sc;
                                ProjectDao.Base.Update(data, it => new { it.Score });
                                f.Close();
                                f.Dispose();
                                Search();
                            }
                        };
                        f.Controls.Add(button);
                        f.ShowDialog();
                    }
                    break;
                case 12:
                    if (data.PreparedDatas?.Count == 0) return;
                    WorkingHoursForm.b.Init(data.Id);
                    break;
                case 13: // 人员变更事件
                    if (view_all.Rows[e.RowIndex].Cells[10].ReadOnly)
                    {
                        return;
                    }
                    var form = CheckUsedStaffForm.b;
                    form.GetStaffByStartEnd(data.FromDate, data.ToDate, data.Id);
                    form.CheckedUser(data.StaffsList?.Select(it => it.UserId).ToList() ?? []);
                    form.action_checked = (list) =>
                    {
                        ProjectStaffDao.Base.Delete(it => it.ProjectId == data.Id);
                        foreach ((int id, string name) in list)
                        {
                            ProjectStaffDao.Base.Add(new ProjectStaff
                            {
                                ProjectId = data.Id,
                                UserId = id,
                                UserName = name
                            });
                        }
                        MessageBox.Show("变更成功");
                        Search();
                    };
                    form.ShowDialog();
                    break;

                case 14: //详情浏览按钮事件
                    ViewProjectForm.b.Init(data.Id);
                    break;
            }
        }

        private void View_all_SelectionChanged(object sender, EventArgs e)
        {
            view_all.ClearSelection();
        }

        private void Btn_first_Click(object sender, EventArgs e)
        {
            _pages.page = 1;
            Search();
        }

        private void Btn_prev_Click(object sender, EventArgs e)
        {
            _pages.page -= 1;
            Search();
        }

        private void Btn_next_Click(object sender, EventArgs e)
        {
            _pages.page++;
            Search();
        }

        private void Btn_last_Click(object sender, EventArgs e)
        {
            _pages.page = _pages.total;
            Search();
        }

        /// <summary>
        /// 设置字体颜色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void View_all_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.RowIndex < 0) return;

            if (view_all.DataSource is not DataTable dt) return;

            (Color back, Color fore) = Program.GetColorByState(Convert.ToInt16(dt.Rows[e.RowIndex]["State"]));
            if (e.CellStyle == null)
                e.CellStyle = new DataGridViewCellStyle
                {
                    BackColor = back,
                    ForeColor = fore
                };
            else
            {
                e.CellStyle.BackColor = back;
                e.CellStyle.ForeColor = fore;
            }
        }

        private void view_all_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            var data = TableData.ElementAt(e.RowIndex);
            var row = view_all.Rows[e.RowIndex];
            row.Cells[10].ReadOnly = !new List<Enum_ProjectState> { Enum_ProjectState.已排期, Enum_ProjectState.实施中 }.Contains(data.State);
        }
    }
}
